package cn.oowoo.rabbitmq.priority;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import cn.oowoo.rabbitmq.config.RabbitExchangeTypeEnum;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 15:18
 * @Description: 消息优先级消费-生产者
 *
 **/
public class PriorityProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(RabbitConfig.EXCHANGE_PRIORITY_NAME, RabbitExchangeTypeEnum.DIRECT.getExchangeType(),false, false, null);

        //声明普通队列（监听此队列无消费优先级效果）
        channel.queueDeclare(RabbitConfig.QUEUE_NORMAL_NAME, true, false, false, null);
        channel.queueBind(RabbitConfig.QUEUE_NORMAL_NAME,RabbitConfig.EXCHANGE_PRIORITY_NAME,RabbitConfig.ROUTING_PRIORITY_KEY);

        //声明优先级队列 (只有监听本队列才能有消费优先级效果)
        Map<String,Object> map = new HashMap<>();
        map.put("x-max-priority",10);
        channel.queueDeclare(RabbitConfig.QUEUE_PRIORITY_NAME, true, false, false, map);
        channel.queueBind(RabbitConfig.QUEUE_PRIORITY_NAME,RabbitConfig.EXCHANGE_PRIORITY_NAME,RabbitConfig.ROUTING_PRIORITY_KEY);


        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder()
                .deliveryMode(2)
                .contentEncoding("UTF-8");
        // 发送消息
        for(int i=0;i<10;i++){
            String msg =  "一条简单消息...." + i;
            if(i == 3 || i== 6 || i == 9){
                builder.priority(5);
            }else{
                builder.priority(1);
            }
            AMQP.BasicProperties properties = builder.build();
            channel.basicPublish(RabbitConfig.EXCHANGE_PRIORITY_NAME,RabbitConfig.ROUTING_PRIORITY_KEY, properties, msg.getBytes());
        }

        //消息发送完毕关闭信道，关闭链接
        channel.close();
        connection.close();
    }

}
